using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class app_frame_function_register : System.Web.UI.Page
{
    string strPagesetRowID = "ps_prc";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    security hdds;
    Hashtable sysVar = new Hashtable();

    protected void Page_init(object sender, EventArgs e)
    {
      //  p_function_register_ft_type_SelectedIndexChanged(null, null);
       // p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
        //this.Theme = Session["Theme"].ToString();
        //this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        setRequestURL();//implemented by sanal on 13 Dec 2007
        this.hdds = new security();

        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                tblcontrols.Visible = false;
                lblKey.Visible = false;
                lblKeyAttr.Visible = false;
                btnReset.Visible = false;
                btnSave.Visible = false;
                btnUpdate.Visible = false;
                return;
            }
        }

        bool blnNoAccess = false;
        //if (Request.QueryString["mn"] != null)
        //{
        //    if (this.hdds.validate_menu(Request.QueryString["mn"].ToString()))
        //    {
        //        blnNoAccess = false;
        //    }
        //}
        if (blnNoAccess)
        {
            Response.Redirect("Error.aspx");
            Response.End();
        }

        if (Request.QueryString["pgs_id"] != null)
        {
            strPagesetRowID = Request.QueryString["pgs_id"];
        }
        if (this.Master.FindControl("Form1") != null) //if (this.FindControl("Form1") != null)
        {
            //loadAllVariables();            
            //GlobalValues.hsSysVar = sysVar;
            frmObj = (HtmlForm)this.Master.FindControl("Form1");//frmObj = (HtmlForm)this.FindControl("Form1")
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);
            //DynamicDisplayI DDI = new DynamicDisplayI();
            //DDI.Load(strPagesetRowID, frmObj, dsePageInfo);

            if (!Page.IsPostBack)
            {
                //loadOwneridDropDown();
                p_prc_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_prc_owner_id.Text = Session["userid"].ToString();
            }

            if (Request.QueryString["VMODE"] != null)
                if (Request.QueryString["VMODE"] == "1")
                {
                    lblHeader.Text = "Processes - View";
                    setData();
                    //return;
                }
            CheckForChangeOwner();
            CheckEditOperation();
        }
        loadDynamicControls();
        //PageInfoLoad PIL = new PageInfoLoad();
       // dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);       
        
        //DynamicDisplayI di = new DynamicDisplayI();
        //Control cc = di.FindControl(tblParamters.Controls, "paramLB0");
        //p_help_help_desc.Visible=false;
        //loadDynamicControls();                
        //CheckEditOperation();
        pr_method_SelectedIndexChanged(null, null);
        if (IsPostBack) return;
        loadCSFiles();
        //pr_method_SelectedIndexChanged(null, null);
        tblParamters.Visible = false;  
        string methodName="";
        p_prc_pr_id.Text = getSeqNumber();
        if (btnUpdate.Visible == true)
            methodName = loadMasterValues();
        pr_dll_name_SelectedIndexChanged(null, null);
        setMethodName(methodName);
        if (btnUpdate.Visible == true)
            loadChildValues();
        //if (Request.QueryString["CPY"]!=null)//to get the new ID
        //    if (Request.QueryString["CPY"].ToString()=="0")
                //p_prc_pr_id.Text = getSeqNumber();
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                loadMasterValues();
                loadChildValues();
                //showParamterContent(true, Request.QueryString["PK"].ToString());
                p_prc_pr_id.Text = getSeqNumber();
                //dd_p_prc_owner_id.SelectedValue = Session["user_afrowid"].ToString();
                p_prc_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_prc_owner_id.Text = Session["userid"].ToString();
            }
        }
        //setData();
        getpageicons();
        isViewMode();
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                ddi.disableControls(this);
                ddi = null;
            }
    }    
    private void setMethodName(string method)
    {
        try
        {
            if (method != "") p_prc_pr_method.SelectedValue = method;
        }
        catch (Exception e)
        {

        }
    }
    private string loadMasterValues()
    {
        try
        {
            string sPageKey = ""; string ret = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return "";
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from sy_prc where af_row_id='" + sPageKey + "'");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    p_prc_af_row_id.Value = sPageKey;
                    p_prc_pr_id.Text = ds.Tables[0].Rows[0]["pr_id"].ToString();
                    p_prc_pr_name.Text = ds.Tables[0].Rows[0]["pr_name"].ToString();
                    p_prc_pr_dll_name.SelectedValue = ds.Tables[0].Rows[0]["pr_dll_name"].ToString();
                    p_prc_pr_desc.Text = ds.Tables[0].Rows[0]["pr_desc"].ToString();
                    ret = ds.Tables[0].Rows[0]["pr_method"].ToString();
                    p_prc_pr_method.SelectedValue = ds.Tables[0].Rows[0]["pr_method"].ToString();
                    //dd_p_prc_owner_id.SelectedValue = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    p_prc_owner_id.Value = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    LoadEditPage LEP = new LoadEditPage();
                    txt_p_prc_owner_id.Text = LEP.GetUserIDFromAfrowid(p_prc_owner_id.Value);
                    LEP = null;
                }
            }
            ds = null;
            hd = null;
            return ret;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadMasterValues: " + e.Message);
            return "";
        }
    }
    private void loadChildValues()
    {
        try
        {
            string sPageKey = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            //ds = hd.GetDataset("select * from sy_prc_prm where af_row_id='" + sPageKey + "'");
            ds = hd.GetDataset("select * from sy_prc_prm where pr_id='" + sPageKey + "'");
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int i = 1;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        Label lb = (Label)tblParamters.Rows[i].Cells[0].Controls[0];
                        if (lb.Text == dr["pr_prm_name"].ToString())
                        {
                            TextBox tb = (TextBox)tblParamters.Rows[i].Cells[1].Controls[0];
                            tb.Text = dr["pr_prm_value"].ToString();
                        }
                        i++;
                    }
                }
            }
            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadChildValues: " + e.Message);
        }
    }
    private void setData()
    {
        string sPageKey = "";
        if (Request.QueryString["PK"] != null)
            sPageKey = Request.QueryString["PK"].ToString();
        Master MA = new Master();
        bool blnStatus = MA.EditOperation(dsePageInfo, frmObj, sPageKey);
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
            Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
        }
        lblKey.Visible = false;
        lblKeyAttr.Visible = false;
        btnSave.Visible = false;
        btnUpdate.Visible = false;
        btnReset.Visible = false;
    }
    private void loadDynamicControls()
    {
        TextBox hf = new TextBox();
        hf.ID = "p_prc_pr_dll_path";
        hf.Text = getDLLPath() + p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "") + ".dll";
        hf.Visible = false;
        lbl_message.Controls.Add(hf);
        hf = new TextBox();
        hf.ID = "p_prc_pr_class";
        hf.Visible = false;
        hf.Text = p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "");
        lbl_message.Controls.Add(hf);
    }
    private void loadCSFiles()
    {
        try
        {
            //string strTemp = Server.MapPath(Request.Url.AbsolutePath);
            //DirectoryInfo di = new DirectoryInfo(strTemp);
            //strTemp = di.Parent.FullName + @"\CustomFunctions\";
            DirectoryInfo di = new DirectoryInfo(getDLLPath());
            FileInfo[] fi = di.GetFiles();
            for (int i = 0; i < fi.Length; i++)
            {
                if (fi[i].Extension.ToLower() == ".cs")
                    p_prc_pr_dll_name.Items.Add(new ListItem(fi[i].Name, fi[i].Name));
            }
            fi = null;
            di = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in Process.aspx:loadCSFiles: " + e.Message);
        }
        if (p_prc_pr_dll_name.Items.Count<1)
            p_prc_pr_dll_name.Items.Add(new ListItem("No Libraries Found", "No Libraries Found"));
    }
    private string getDLLPath()
    {
        string strTemp = Server.MapPath(Request.Url.AbsolutePath);
        DirectoryInfo di = new DirectoryInfo(strTemp);
        strTemp = di.Parent.FullName + @"\CustomFunctions\";
        //strTemp = "D:" + @"\CustomFunctions\";
        di = null;
        return strTemp;
    }
    private string getSeqNumber()
    {
        try
        {
            int ret = 0;
            HDDatabase hd = new HDDatabase();
            DataSet ds = hd.GetDataset("SELECT max(cast(pr_id as int)+1) AS Count FROM sy_prc");
            if (ds == null)
            {
                ret = 1000;
            }
            else
            {
                try
                {
                    ret = Convert.ToInt32(ds.Tables[0].Rows[0]["Count"].ToString());
                }
                catch (Exception e)
                { }
                if (ret < 1000)
                    ret = ret + 1000;
            }
            hd = null;
            return ret.ToString();
        }
        catch (Exception e)
        {
            return "1000";
        }
    }
    private bool CheckEditOperation()
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        if (Page.IsPostBack == false)
        {
            if (Request.QueryString["PK"] != null)
            {
                strPageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
            }
            if (IsEdit)
            {
                Master MA = new Master();
                blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
                if (blnStatus == false)
                {
                    strErrMessage = MA.ErrorMessage;
                    Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
                }
            }
        }
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                lblHeader.Text = "Processes - Copy";
                btnSave.Visible = true;
                btnUpdate.Visible = false;
            }
        }
        else if (Request.QueryString["PK"] == null)
        {
            btnSave.Visible = true;
            btnUpdate.Visible = false;
        }
        else
        {
            lblHeader.Text = "Processes - Edit";
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }
        return blnStatus;
    }



    private bool SaveData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowID, frmObj, dsePageInfo,true);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    private bool UpdateData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowID, frmObj, dsePageInfo,false);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    private bool validate()
    {
        try
        {
            if (p_prc_pr_dll_name.Items.Count<1)
            {
                lbl_message.Text ="<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;No class files has been created.";//changed by prithi on 07-Aug-2008
                return false;
            }
            return true;
        }
        catch (Exception e)
        {
            return true;
        }
    }
    private void setRequestURL()//implemented by sanal on 13 Dec 2007
    {
        if (!IsPostBack)
            //hfRequestURL.Value = Request.UrlReferrer.ToString();
            hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
    }
    private string getURL()//implemented by sanal on 13 Dec 2007
    {
        try
        {
            return hfRequestURL.Value;
            //return "DisplayGrid.aspx?mn=" + Request.QueryString["mn"].ToString() + "&pgs_id=" + Request.QueryString["pgs_id"].ToString();
        }
        catch (Exception e)
        {
            return "";
        }
    }
    protected void btnSave_ServerClick(object sender, EventArgs e)
    {        
        //return;      
        if (!validate()) return;
        if (SaveData())
        {
            //Response.Write("Data Inserted Successfully");
            if (saveChildRecords(false))
            {
                //lbl_message.Text = "Data Inserted Successfully";
                string ret = getURL();//implemented by sanal on 13 Dec 2007
                if (ret != "")
                    Response.Redirect(ret, true);
                else
                    lbl_message.Text = "&nbsp;<img src='Images/tick4.gif' border='0'>&nbsp;Data Updated Successfully"; //changed by prithi on 07-Aug-2008
                //p_prc_pr_id.Text = getSeqNumber();
            }
            else
                lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Unable to save the parameters."; //changed by prithi on 07-Aug-2008
        }
        else
        {
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error:" + ErrorMessage;
        }
    }
    private bool saveChildRecords(bool updateMode)
    {        
        string paramName = ""; string paramValue = "";
        string query = "";
        ScreenReader sr = new ScreenReader();
        try
        {
            HDDatabase hd = new HDDatabase();
            if (updateMode)
            {
                //hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand("delete from sy_prc_prm where af_row_id='" + p_prc_af_row_id.Value + "'"));
                hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand("delete from sy_prc_prm where pr_id='" + p_prc_af_row_id.Value + "'"));
            }
            for (int i = 1; i < tblParamters.Rows.Count; i++)
            {
                //DynamicDisplayI di = new DynamicDisplayI();
                //Control cc = di.FindControl(tblParamters.Controls, "paramLB" + i.ToString());
                Label lb = (Label)tblParamters.Rows[i].Cells[0].Controls[0];
                paramName = lb.Text;
                TextBox tb = (TextBox)tblParamters.Rows[i].Cells[1].Controls[0];
                paramValue = tb.Text;
                //query = "insert into sy_prc_prm(af_row_id,pr_id,pr_prm_name,pr_prm_value) values ('"+ p_prc_af_row_id.Value + "','" + p_prc_pr_id.Text + "','" + paramName + "','" + paramValue + "')";
                query = "insert into sy_prc_prm(af_row_id,pr_id,pr_prm_name,pr_prm_value) values ('" + sr.getHashKey() + "','" + p_prc_af_row_id.Value + "','" + paramName + "','" + paramValue + "')";
                hd.ExecuteCmdObj(new System.Data.SqlClient.SqlCommand(query));
            }
            hd = null;
            sr = null;
            return true;
        }
        catch (Exception e)
        {
            sr = null;
            return false;
        }
    }
    private string checkForErrors(string content, bool isExpression)
    {
        MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();            
        try
        {            
            sc.Language = "VBScript";
            if (!isExpression)
                sc.AddCode(content);
            else
                sc.Eval(content);
            sc = null;
            return "success";
        }
        catch (Exception e)
        {
            sc = null;
            return e.Message;
        }
    }
    private int getFunctionCount(string content)
    {
        MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();            
        MSScriptControl.Procedures pr;
        int ret=0;
        try
        {            
            sc.Language = "VBScript";
            sc.AddCode(content);
            pr = sc.Procedures;
            ret = pr.Count;
            sc = null;            
        }
        catch (Exception e)
        {
            sc = null;
            ret = -1;
        }
        return ret;
    }
    private void addTextBox(string controlID,string value)
    {
        TextBox tb = new TextBox();
        tb.ID = controlID;
        tb.Text = value;
        if (frmObj!=null) frmObj.Controls.Add(tb);
    }
    protected void btnUpdate_ServerClick(object sender, EventArgs e)
    {
        if (!validate()) return;
        if (UpdateData())
        {
            if (saveChildRecords(true))
            {
                lbl_message.Text = "&nbsp;<img src='Images/tick4.gif' border='0'>&nbsp;Data Updated Successfully";//changed by prithi on 07-Aug-2008
                //p_prc_pr_id.Text = getSeqNumber();
            }
            else
                lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Unable to save the parameters.";//changed by prithi on 07-Aug-2008
        }
        else
        {
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. Error:" + ErrorMessage;
        }
    }    
    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    private string compileCS(string content, string outputFileName,string inptFileName)
    {
        //System.Diagnostics.Process.Start(@"D:\Sanal\Study\WebProjects\AppFrameCompilerApp\AppFrameCompilerApp\bin\Debug\AppFrameCompilerApp.exe", inptFileName + " " + outputFileName);
        //return "success";
        string ret="";
        System.CodeDom.Compiler.CodeDomProvider cc = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#");
        //System.CodeDom.Compiler.ICodeCompiler cc = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();        
        System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters();
        cp.ReferencedAssemblies.Add("system.dll"); //includes
        cp.GenerateExecutable = false; //generate executable
        cp.OutputAssembly = outputFileName;        
        tryDelete(outputFileName);
        //After setting the parameters, compile the code and get the results. Check out for errors, if any.

        //System.CodeDom.Compiler.CompilerResults cr = cc.CompileAssemblyFromFile(cp, inptFileName);
        System.CodeDom.Compiler.CompilerResults cr = cc.CompileAssemblyFromSource(cp, content);
        if (cr.Errors.HasErrors)
        {
            ret = cr.Errors[0].ErrorText;
            createDLLfromCS(inptFileName, outputFileName);
        }
        else
            ret = "success";
        cr = null;
        cp = null;
        cc = null;
        return ret;

    }
    private void createDLLfromCS(string inpfile, string opFile)
    {
        try
        {
            if (frameWorkExists())
            {
                string path = "";
                //Environment.SpecialFolder.MyComputer
                path = Environment.GetFolderPath(Environment.SpecialFolder.System).ToString().Replace("system32", "") + @"Microsoft.NET\Framework\V2.0.50727";
                if (System.IO.Directory.Exists(path))
                {
                    System.Diagnostics.Process pr = System.Diagnostics.Process.Start(path + @"\csc.exe", "/t:library /out:" + opFile + " " + inpfile);
                    pr.WaitForExit();
                    pr = null;
                }
            }
        }
        catch (Exception e)
        {
        }
    }
    private bool frameWorkExists()
    {
        try
        {
            int ret = 0;
            Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.RegistryKey rk1 = rk.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v2.0.50727");
            //            %windir%\Microsoft.NET\Framework\V2.0.50727
            ret = (int)rk1.GetValue("Install");
            return ret > 0;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private void tryDelete(string fileName)
    {
        try
        {
            File.Delete(fileName);
        }
        catch (Exception e)
        {

        }
    }
    protected void pr_dll_name_SelectedIndexChanged(object sender, EventArgs e)
    {        
        ////p_function_register_fr_selected_fnExp
        //HDDatabase hd = new HDDatabase();
        //DataSet ds = hd.GetDataset("Select * from my_function where fn_type='" + pr_dll_name.SelectedValue + "'");
        //pr_method.Items.Clear();
        //if (ds != null)
        //{
        //    if (ds.Tables[0].Rows.Count > 0)
        //    {
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            pr_method.Items.Add(new ListItem(dr["fn_name"].ToString(),dr["fn_name"].ToString()));
        //        }
        //    }
        //}
        //p_function_register_fr_selected_fnExp_SelectedIndexChanged(null, null);
        p_prc_pr_method.Items.Clear();
        if (p_prc_pr_dll_name.SelectedValue.Length > 0)
        {
            AppFrameCompiler.csCompiler ac = new AppFrameCompiler.csCompiler();
            string dllPath = getDLLPath();

            string fileInp = dllPath + p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "") + ".dll";
            string typeFullName = p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "") + "." + p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "");
            ////string ret = ac.compileAndSave(getFileContent(dllPath+ p_prc_pr_dll_name.SelectedValue),fileInp);
            string ret = compileCS(getFileContent(dllPath + p_prc_pr_dll_name.SelectedValue), fileInp, dllPath + p_prc_pr_dll_name.SelectedValue);
            //string ret = ac.compile(removeUpToNameSpaceName(appendMethod(getFileContent(getClassFile(p_compiler_category.SelectedValue)), p_compiler_compiler_code.Text), p_compiler_category.SelectedValue));
            ac = null;
            
            if (File.Exists(fileInp))
            {
                //System.Reflection.MethodInfo[] Methods = getMethods(fileInp, typeFullName);
                ArrayList Methods = getMethodsInArrayListUsingType(fileInp, typeFullName);
                //ArrayList Methods = getMethodsInArrayListUsingLoad(fileInp, typeFullName);
                if (Methods == null)
                {
                    p_prc_pr_method.Items.Add(new ListItem("No Methods Defined", ""));
                }
                else
                {
                    for (int i = 0; i < Methods.Count; i++)
                    {
                        p_prc_pr_method.Items.Add(new ListItem(Methods[i].ToString(), Methods[i].ToString()));
                    }
                }
                Methods = null;
            }
            else
                p_prc_pr_method.Items.Add(new ListItem("No Methods Defined", ""));
           //sanal
            pr_method_SelectedIndexChanged(null, null);
        }
    }
    private ArrayList getParamters1(string assemblyFileName, string typeFullName,string methodName)
    {
        ArrayList ret = new ArrayList();
        try
        {
            //string assemblyPath = @"E:\Sanal\Study\WebProjects\testApp\testApp\bin\sendEMail.dll";
            //System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFrom(assemblyFileName);
            System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFile(assemblyFileName);
            //object objInstance = myAssembly.CreateInstance("sendEMail.csSendEmail");
            object objInstance = myAssembly.CreateInstance(typeFullName);
            //myAssembly.CreateInstance(
            System.Reflection.BindingFlags flags = (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
            System.Reflection.MethodInfo[] mi = objInstance.GetType().GetMethods();
            for (int i = 0; i < mi.Length; i++)
            {
             //   ret.Add(mi[i].Name);
                if (mi[i].Name.ToLower() == methodName.ToLower())
                {
                    
                    //object[] tt = mi[i].GetCustomAttributes();                    
                    //System.Reflection.MethodAttributes ma = mi[i].Attributes;
                    Type[] ob = mi[i].GetGenericArguments();
                    System.Reflection.ParameterInfo[] pi = mi[i].GetParameters();
                    for (int k = 0; k < pi.Length; k++)
                    {
                        ret.Add(pi[k].Name);
                    }
                    pi = null;
                    break;
                }
            }
            mi = null;
            objInstance = null;            
            myAssembly = null;
            System.GC.Collect();
            return ret;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    private ArrayList getParameters(string csFileName, string methodName)
    {
        ArrayList alParams = new ArrayList();
        StreamReader sr = new StreamReader(csFileName);
        string content = "";// = sr.ReadToEnd(csFileName);
        do
        {
            content = sr.ReadLine();
            int startPos = 0; int endPos = 0;
            if (content.IndexOf(methodName) > 0 && content.IndexOf("(") > content.IndexOf(methodName) && content.IndexOf(")") > content.IndexOf(methodName))
            {
                startPos = content.IndexOf(methodName) + methodName.Length;
                endPos = content.IndexOf(")");
                content = content.Substring(startPos+1, endPos-startPos-1);
                string[] param = content.Split(',');
                for (int i = 0; i < param.Length; i++)
                {
                    string[] splits = content.Split(' ');
                    alParams.Add(splits[1]);
                }
                break;
            }
        }
        while(!sr.EndOfStream);
        sr.Close(); sr = null;
        return alParams;
    }
    private ArrayList getParameters(string assemblyFileName, string typeFullName, string methodName)
    {
        ArrayList ret = new ArrayList();
        try
        {
            //string assemblyPath = @"E:\Sanal\Study\WebProjects\testApp\testApp\bin\sendEMail.dll";
            //System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFrom(assemblyFileName);
            System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFile(assemblyFileName);
            Type[] types = myAssembly.GetExportedTypes();
            System.Reflection.MethodInfo[] mi;
            foreach (Type t in types)
            {
                if (!t.IsClass)
                    continue;
                mi = t.GetMethods();
                for (int i = 0; i < mi.Length; i++)
                {
                    //   ret.Add(mi[i].Name);
                    if (mi[i].Name.ToLower() == methodName.ToLower())
                    {

                        //object[] tt = mi[i].GetCustomAttributes();                    
                        //System.Reflection.MethodAttributes ma = mi[i].Attributes;                        
                        System.Reflection.ParameterInfo[] pi = mi[i].GetParameters();
                        for (int k = 0; k < pi.Length; k++)
                        {
                            ret.Add(pi[k].Name);
                        }
                        pi = null;
                        break;
                    }
                }
            }            
            mi = null;
            //objInstance = null;
            myAssembly = null;
            System.GC.Collect();
            return ret;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    public Object LoadDLL(string DLLName, string ClassName, object[] args)
    {
        Object objTmp = null;
        try
        {
            //BindingFlags flags = 0;
            //Binder bi = null;
            //object[] attr = null;
            System.Reflection.Assembly objAssembly = System.Reflection.Assembly.LoadFrom(DLLName);
            objTmp = objAssembly.CreateInstance(ClassName);

            //objTmp = objAssembly.CreateInstance(ClassName, true, flags, bi, args, Ci, attr);
        }
        catch (Exception ex)
        {
            return null;
        }
        return objTmp;
    }

    private ArrayList getMethodsInArrayListUsingLoad(string assemblyFileName, string typeFullName)
    {
        ArrayList ret = new ArrayList();
        try
        {
            object obj = LoadDLL(assemblyFileName, typeFullName, null);
            Type t = obj.GetType();
            System.Reflection.MethodInfo[] mi = t.GetMethods();
            for (int i = 0; i < mi.Length; i++)
            {
                ret.Add(mi[i].Name);
            }
            mi = null;
            t = null;
            obj = null;
            return ret;
        }
        catch (Exception e)
        {
            return ret;
        }
    }
    private ArrayList getMethodsInArrayListUsingType(string assemblyFileName, string typeFullName)
    {
        ArrayList ret = new ArrayList();
        System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFile(assemblyFileName);
        
        //Type[] types = myAssembly.GetExportedTypes();
        Type[] types = myAssembly.GetTypes();
        System.Reflection.BindingFlags flags = (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public |
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
        System.Reflection.MethodInfo[] mi;
        foreach (Type t in types)
        {
            if (!t.IsClass)
                continue;
            mi = t.GetMethods(flags);
            //mi = t.GetMethods();
            for (int i = 0; i < mi.Length; i++)
            {
                ret.Add(mi[i].Name);
            }            
        }
        types = null;
        mi = null;
        //objInstance = null;
        myAssembly = null;
        System.GC.Collect();
        return ret;
    }
    private ArrayList getParametersInArrayListUsingType(string assemblyFileName, string typeFullName,string methodName)
    {
        ArrayList ret = new ArrayList();
        if (!File.Exists(assemblyFileName)) return ret;
        System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFile(assemblyFileName);
        Type[] types = myAssembly.GetExportedTypes();
        System.Reflection.MethodInfo[] mi;
        foreach (Type t in types)
        {
            if (!t.IsClass)
                continue;
            mi = t.GetMethods();
            for (int i = 0; i < mi.Length; i++)
            {
                //ret.Add(mi[i].Name);
                if (mi[i].Name.ToLower() == methodName.ToLower())
                {
                    System.Reflection.ParameterInfo[] pi = mi[i].GetParameters();
                    for (int k = 0; k < pi.Length; k++)
                    {
                        ret.Add(pi[k].Name);
                    }
                    break;
                }
            }
        }
        types = null;
        mi = null;
        //objInstance = null;
        myAssembly = null;
        System.GC.Collect();
        return ret;
    }
    private ArrayList getMethodsInArrayList(string assemblyFileName, string typeFullName)
    {
        ArrayList ret = new ArrayList();
        try
        {
            //string assemblyPath = @"E:\Sanal\Study\WebProjects\testApp\testApp\bin\sendEMail.dll";
            System.Reflection.Assembly myAssembly = System.Reflection.Assembly.LoadFrom(assemblyFileName);
            //object objInstance = myAssembly.CreateInstance("sendEMail.csSendEmail");
            object objInstance = myAssembly.CreateInstance(typeFullName);
            System.Reflection.MethodInfo[] mi = objInstance.GetType().GetMethods();
            for (int i = 0; i < mi.Length; i++)
                ret.Add(mi[i].Name);               
            mi = null;
            objInstance = null;
            myAssembly = null;
            System.GC.Collect();
            return ret;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    private string getFileContent(string fileName)
    {
        string content = "";
        try
        {
            StreamReader sr = new StreamReader(fileName);
            content = sr.ReadToEnd();
            sr.Close(); sr = null;
            return content;
        }
        catch (Exception e)
        {
            return "";
        }
    }
    protected void pr_method_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (!IsPostBack) return;
        //return;
        tblParamters.CellPadding = 3;
        tblParamters.CellSpacing = 0;
        tblParamters.BorderWidth = 0;
        if (p_prc_pr_method.SelectedValue == "") return;
        string dllPath = getDLLPath();
        string fileInp = dllPath + p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "") + ".dll";
        string typeFullName = p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "") + "." + p_prc_pr_dll_name.SelectedValue.Replace(".cs", "").Replace(".CS", "");
       
        ArrayList al = new ArrayList();
        al = getParametersInArrayListUsingType(fileInp, typeFullName, p_prc_pr_method.SelectedValue);
        //al = getParameters(dllPath + pr_dll_name.SelectedValue, pr_method.SelectedValue);
        int count = 0;
        for (int j = 1; j < tblParamters.Rows.Count; j++)
        {
            tblParamters.Rows.RemoveAt(j - count); count++;
        }
        if (al.Count > 0)
        {
            HtmlTable ht = new HtmlTable();
            ht.EnableViewState = true;
            ht.ID = "DynamicTable";
            ht.Border = 0;
            ht.CellPadding = 0;
            ht.CellSpacing = 0;
            for (int i = 0; i < al.Count; i++)
            {
                TableRow hr = new TableRow();
                hr.ID = "Row" + i.ToString();
                hr.EnableViewState = true;
                TableCell hc1 = new TableCell();
                hc1.ID = "cell1" + i.ToString();
                hc1.EnableViewState = true;                
                hc1.Controls.Add(getLabel("paramLB" + i.ToString(), al[i].ToString()));
                TableCell hc2 = new TableCell();
                hc2.ID = "cell2" + i.ToString();
                hc2.EnableViewState = true;
                hc2.Width = 30;
                hc2.Controls.Add(getTextBox("paramTB" + i.ToString()));// = ;
                TableCell hc3 = new TableCell();
                hc3.ID = "cell3" + i.ToString();
                hc3.EnableViewState = true;
                //hc3.
                hc3.Controls.Add(getDropDownBox("paramDD" + i.ToString()));// = ;
                hr.Cells.AddRange(new TableCell[] { hc1, hc2, hc3 });
                tblParamters.Rows.Add(hr);                          
            }
            ht.Visible = true;
            tblParamters.Visible = true;
        }
        else
            tblParamters.Visible = false;              
    }
    private void addControls(string[] args)
    {
        for (int i = 0; i < args.Length; i++)
        {
            TableRow hr = new TableRow();
            hr.ID = "Row" + i.ToString();
            hr.EnableViewState = true;
            TableCell hc1 = new TableCell();
            hc1.ID = "cell1" + i.ToString();
            hc1.EnableViewState = true;
            hc1.Controls.Add(getLabel("paramLB" + i.ToString(), args[i]));
            TableCell hc2 = new TableCell();
            hc2.ID = "cell2" + i.ToString();
            hc2.EnableViewState = true;
            hc2.Controls.Add(getTextBox("paramTB" + i.ToString()));// = ;
            TableCell hc3 = new TableCell();
            hc3.ID = "cell3" + i.ToString();
            hc3.EnableViewState = true;
            //hc3.
            hc3.Controls.Add(getDropDownBox("paramDD" + i.ToString()));// = ;
            hr.Cells.AddRange(new TableCell[] { hc1, hc2, hc3 });
            tblParamters.Rows.Add(hr);
        }
    }
    private Control getLabel(string id,string text)
    {
        Label lb = new Label();
        lb.ID = id;
        lb.Text = text;
        lb.EnableViewState = true;
        //tb.Font = "Arial";
        return lb;
    }
    private Control getTextBox(string id)
    {
        TextBox tb = new TextBox();
        //tb.MaxLength = 10;
        //tb.Width = 120;
        tb.EnableViewState = true;
        tb.ID = id;        
        //tb.Font = "Arial";
        return tb;
    }
    protected void dd_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            DropDownList dls = (DropDownList)sender;
            //if (dls.SelectedIndex == 0) return;
            string ss = dls.ID;
            ss = "paramTB" + ss.TrimStart("paramDD".ToCharArray());            
            DynamicDisplayI di = new DynamicDisplayI();
            Control cc = di.FindControl(this.Form.Controls, ss);
            di = null;
            TextBox tb = (TextBox)cc;
            if (dls.SelectedIndex == 0)
                tb.Text = "";
            else
                tb.Text = "{!" + dls.SelectedValue + "}";
        }
        catch (Exception ee)
        {

        }
    }
    private Control getDropDownBox(string id)
    {
        DropDownList dd = new DropDownList();
        dd.SelectedIndexChanged+=new EventHandler(dd_SelectedIndexChanged);
        dd.ID = id;        
        dd.EnableViewState = true;
        dd.AutoPostBack = true;      
        //get system variables and load here
        dd.Items.Add(new ListItem("-- Select System Variables --", "-- Select System Variables --"));
        HDDatabase hd = new HDDatabase();
        DataSet ds = new DataSet();
        ds = hd.GetDataset("Select distinct sy_var_name from sy_var");
        hd = null;
        if (ds.Tables.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                dd.Items.Add(new ListItem(dr["sy_var_name"].ToString(), dr["sy_var_name"].ToString()));
            }
        }
        return dd;
    }

    private void getpageicons()// Added by srivatsan to get page icon
    {
        PageIcons icons = new PageIcons();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();

            lblHeader.Text = "&nbsp;" + icons.geticontextfrompageset(strPagesetRowID, 2) + "&nbsp;" + lblHeader.Text;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            lblHeader.Text = "&nbsp;<img src=" + PageIcons.strdefaulticon.ToString() + "></img>&nbsp;" + lblHeader.Text;
        }
        finally
        {
            icons = null;
            Hdd = null;
        }

    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {
            string strBindRowID = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
            BC.Bind(strBindRowID, dd_p_prc_owner_id, ref dt,null);

            if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
            {
                dd_p_prc_owner_id.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
            }

            if (Request.QueryString["PK"] == null)
            {
                dd_p_prc_owner_id.SelectedValue = Session["user_afrowid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    dd_p_prc_owner_id.SelectedValue = Session["user_afrowid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }

    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {

                txt_p_prc_owner_id.Enabled = false;

            }
            else
            {
                PageCommonFunctions PCF = new PageCommonFunctions();
                PCF.AddSearchLink(ref tdownerid, "owner_id", "p_prc_owner_id", "txt_p_prc_owner_id", "f496930dfe0b690f");
                PCF = null;
            }

            sec = null;
        }
        catch
        {

        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
}
